package smartcrud.spring.controllers.cms;

import java.io.File;
import java.io.FileOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.kitten.core.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import smartcrud.spring.models.cms.Attachment;
import smartcrud.spring.models.cms.AttachmentService;

@Controller
@RequestMapping("/upload")
public class UploadController {
	private static final Log logger = LogFactory.getLog(UploadController.class);
	@Autowired
	private AttachmentService attachmentService;

	@RequestMapping(value = "/image", method = RequestMethod.POST)
	@ResponseBody
	public String image(HttpServletRequest request,
			HttpSession session,
			@RequestParam("filedata") MultipartFile file) throws Exception {

		// 将图片按日期分开存放，方便管理
		final String prefix = "upload/images/"
				+ DateUtil.getFormatedDate("yyyy/MM_dd");

		// 存放到web根目录下,如果日期目录不存在，则创建,
		// 注意 request.getRealPath("/") 已经标记为不推荐使用了.
		final String realPath = session.getServletContext().getRealPath(prefix);
		logger.info(realPath);
		File dir = new File(realPath);
		if (!dir.exists()) {
			dir.mkdirs();
		}

		// 以下是真正的上传部分
		String error = "";
		// 取得原文件名
		final String originalName = file.getOriginalFilename();
		// 取得文件后缀
		String fileExt = originalName.substring(originalName.lastIndexOf(".") + 1);
		// 按时间戳生成图片文件名
		String picture = DateUtil.getFormatedDate("yyyyMMddHHmmss") + "."
				+ fileExt;
		Attachment attachment = new Attachment();
		try {

			IOUtils.copy(file.getInputStream(), new FileOutputStream(new File(dir, picture)));

			//向attachment表中插入一条post_id为空的图片记录
			attachment.setDownloadCount(0);
			attachment.setFileType("image");
			attachment.setSize((int) file.getSize());
			attachment.setOriginalName(originalName);
			attachment.setUrl(prefix + "/" + picture);
			attachment = attachmentService.createAttachment(attachment);

		} catch (Exception e) {
			logger.error("error:", e);
			error = e.getMessage();
		}
		String http = "http://" + request.getServerName()
	                + ":"  
	                + request.getServerPort()      
	                + request.getContextPath();   
		String url =  http + "/" + prefix + "/" + picture;
		//注意这里的格式(见xheditor文档)
		//{'err':'',msg:{'url':'http://localhost:9080/spring/upload/images/2012/11_11/20121111015039.jpg','localname':'我的头像.jpg','id':'63'}}
		String json = String.format("{'err':'%s',msg:{'url':'%s','localname':'%s','id':'%s'}}", error, url, originalName, attachment.getId());
		return json;
	}
}
